from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area


class AreasView(View):
    def get(self, request):
        # province_list = cache.get('provinces')
        # if not province_list:
            # 1.查询所有省份
        try:
            provinces = Area.objects.filter(parent=None)
            # 2.转换为字典
            province_list = []
            for province in provinces:
                province_list.append({"id": province.id, "name": province.name})
            # cache.set("provinces", province_list, 3600 * 24)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "查询失败"})

        # 3.返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "province_list": province_list})


class SubAreaView(View):
    def get(self, request, id):
        # sub_data = cache.get('sub_areas%s' % id)
        # if not sub_data:
        #     print('获取sub_data')
        try:
            # 1.获取id，根据id查询省或市的对象
            parent_obj = Area.objects.get(id=id)

            # 2.获取省或市的下一级所有数据
            sub_objs = parent_obj.subs.all()

            # 3.转为字典
            subs = []
            for sub in sub_objs:
                subs.append({"id": sub.id, "name": sub.name})

            sub_data = {"id": id, "name": parent_obj.name, "subs": subs}

            # 取出sub_data
            # cache.set('sub_areas%s' % id, sub_data, 3600 * 24)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "查询失败"})
        # else:
        #     print('缓存sub_data')
        # 4.返回数据
        return JsonResponse({"code": 0, "errmsg": "ok", "sub_data": sub_data})
